package com.oscar.practice.shiro.biz.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

import com.google.code.kaptcha.Constants;

/**
 * 验证码拦截器
 *
 * @author tongyufu
 *
 */
@Component
public class CaptchaValidateFilter extends AccessControlFilter {

    private String captchaEnable = "N";

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response,
                                      Object mappedValue) throws Exception {
        HttpServletRequest req = WebUtils.toHttp(request);
        Object captcha = req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        String reqCaptcha = req.getParameter("captcha");

        req.setAttribute("captchaEnable", captchaEnable);
        //判断验证码是否禁用
        if ("N".equals(captchaEnable) || !"post".equalsIgnoreCase(req.getMethod())) {
            return true;
        }
        if (captcha == null || StringUtils.isBlank(reqCaptcha)
            || !StringUtils.equals(captcha.toString(), reqCaptcha)) {
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request,
                                     ServletResponse response) throws Exception {
        //如果验证码失败了，存储失败key属性
        request.setAttribute("CaptchaValidate", "captcha error");
        return true;
    }

}
